using B.S.Medical.Api.Read.Application.Command.Department;
using B.S.Medical.Api.Read.DTOS;
using B.S.Medical.Domain.Department;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Medical.Api.Read.Application.Handler.Department
{
    /// <summary>
    /// 根据院区ID查询科室的处理器
    /// </summary>
    public class GetDepartmentByCampusHandler : IRequestHandler<GetDepartmentByCampusCommand, ApiResult<List<DepartmentListDTO>>>
    {
        private readonly IBaseRepository<ManageModel> departmentRepo;
        private readonly ILogger<GetDepartmentByCampusHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepo">科室仓储</param>
        /// <param name="logger">日志</param>
        public GetDepartmentByCampusHandler(
            IBaseRepository<ManageModel> departmentRepo,
            ILogger<GetDepartmentByCampusHandler> logger)
        {
            this.departmentRepo = departmentRepo;
            this.logger = logger;
        }

        /// <summary>
        /// 处理根据院区ID查询科室的请求
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>科室列表结果</returns>
        public Task<ApiResult<List<DepartmentListDTO>>> Handle(GetDepartmentByCampusCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有未删除且状态为启用的科室数据，并按照院区ID筛选
                var departments = departmentRepo.GetAll()
                    .Where(d => !d.IsDeleted && d.Status && d.CampusId == request.CampusId)
                    .ToList();

                // 转换为DTO
                var result = departments.Select(d => new DepartmentListDTO
                {
                    Id = d.Id,
                    DepartmentName = d.DepartmentName
                }).ToList();

                // 构建返回结果
                return Task.FromResult(new ApiResult<List<DepartmentListDTO>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取科室列表成功",
                    Data = result
                });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取科室列表时发生错误");
                return Task.FromResult(new ApiResult<List<DepartmentListDTO>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取科室列表失败：" + ex.Message
                });
            }
        }
    }
} 